package com.easy.service.impl;

import com.easy.annotation.LogMethod;
import com.easy.bean.Order;
import com.easy.bean.OrderDetail;
import com.easy.mapper.OrderDetailMapper;
import com.easy.mapper.OrderMapper;
import com.easy.mapper.ScheduleMapper;
import com.easy.service.OrderDetailService;
import com.easy.util.Page;
import com.easy.util.SYS;
import com.easy.util.TicketInventoryManager;
import com.easy.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class OrderDetailServiceImpl implements OrderDetailService {

    AtomicInteger atomicInteger = new AtomicInteger();

    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    ScheduleMapper scheduleMapper;
    @Autowired
    OrderMapper orderMapper;



    @Autowired
    TicketInventoryManager ticketInventoryManager;


    @Override
    @LogMethod(serviceName = "添加订单细节", recordParam = true, recordReturn = true)
    public OrderDetail add(OrderDetail orderDetail) {
        orderDetailMapper.add(orderDetail);
        OrderDetail result = orderDetailMapper.one(orderDetail.getId());
        return result;
    }

    @Override
    @LogMethod(serviceName = "删除订单细节", recordParam = true, recordReturn = true)
    @CachePut(value = "orderDetail", key = "#p0.id")
    public int del(Integer id) {
        return orderDetailMapper.del(id);
    }
    @Override
    @LogMethod(serviceName = "管理员删除订单细节", recordParam = true, recordReturn = true)
    @CachePut(value = "orderDetail", key = "#p0")
    public int finishdel(String orderId) {
        return orderDetailMapper.finishdel(orderId);
    }

    @Override
    @LogMethod(serviceName = "修改订单细节", recordParam = true, recordReturn = true)
    @CachePut(value = "orderDetail", key = "#p0.id")
    public OrderDetail edit(OrderDetail orderDetail) {
        orderDetailMapper.edit(orderDetail);
        OrderDetail result = orderDetailMapper.one(orderDetail.getId());
        return result;
    }

    @Override
    @CachePut(value = "orderDetail", key = "#p0")
    public List<OrderDetail> all(String realName) {
        List<OrderDetail> result = orderDetailMapper.all(realName);
        return result;
    }

    @Override
    @LogMethod(serviceName = "管理员修改订单细节", recordParam = true, recordReturn = true)
    @CachePut(value = "orderDetail", key = "#p0.id")
    public OrderDetail finishEdit(OrderDetail orderDetail) {
        orderDetailMapper.edit(orderDetail);
        OrderDetail result = orderDetailMapper.one(orderDetail.getId());
        return result;
    }

    @Override
    @Cacheable(value = "orderDetail", key = "#p0")//也可以#p0表示第一个参数
    public OrderDetail one(Integer id) {
        return orderDetailMapper.one(id);
    }

    @Override
    @Cacheable(value = "orderDetail", key = "#p0")//也可以#p0表示第一个参数
    public void page(Page page, OrderDetail orderDetail,String token) {
        Object option = TokenUtil.getOption(token, SYS.TOKEN_KEY_ID);
        Integer userId = Integer.valueOf(option.toString());
        orderDetail.setUserId(userId);
        int count = orderDetailMapper.pageCount(orderDetail);
        Object data = orderDetailMapper.page(page,orderDetail);
        page.setCount(count);
        page.setData(data);
    }
    @Override
    @Cacheable(value = "orderDetail", key = "#p0")//也可以#p0表示第一个参数
    public void commitPage(Page page, OrderDetail orderDetail,String token) {
        Object option = TokenUtil.getOption(token, SYS.TOKEN_KEY_ID);
        Integer userId = Integer.valueOf(option.toString());
        orderDetail.setUserId(userId);
        System.out.println(orderDetail);
        System.out.println(userId);
        int count = orderDetailMapper.commitPageCount(orderDetail,userId);
        Object data = orderDetailMapper.commitPage(page,orderDetail,userId);
        page.setCount(count);
        page.setData(data);
    }

    @Override
    @Cacheable(value = "orderDetail", key = "#p0")//也可以#p0表示第一个参数
    public void finishPage(Page page, OrderDetail orderDetail) {
        int count = orderDetailMapper.finishPageCount(orderDetail);
        Object data = orderDetailMapper.finishPage(page,orderDetail);
        page.setCount(count);
        page.setData(data);
    }



    @Override
    @LogMethod(serviceName = "取消订单", recordParam = true, recordReturn = true)
    public int cancel(Integer id) {
//        new TicketInventoryManager();
        OrderDetail orderDetail = orderDetailMapper.one(id);
        if (orderDetail == null) {
            System.err.println("订单不存在: " + id);
            return 0;
        }
        //增加票数
        boolean success = ticketInventoryManager.addTickets(orderDetail.getScheduleId(), 1);
        if(success){
            //设置订单状态
            orderDetail.setStatus("取消订单");
            orderDetailMapper.edit(orderDetail);
            orderMapper.cancel(orderDetail.getOrderId());

            System.out.println("取消订单，班次 " + orderDetail.getScheduleId() + " 剩余票数: " +
                    ticketInventoryManager.getRemainingTickets(orderDetail.getScheduleId()));
            return 1;
        }
        else{
            return 0;
        }
    }


@Override
@LogMethod(serviceName = "提交订单", recordParam = true, recordReturn = true)
public String commit(Integer id) {
    // 获取订单详情
    OrderDetail orderDetail = orderDetailMapper.one(id);
    if (orderDetail == null) {
        System.err.println("订单不存在: " + id);
        return "订单不存在";
    }
    // 检查订单状态，避免重复处理
    if ("已支付".equals(orderDetail.getStatus())) {
        System.out.println("订单已支付: " + id);
        return "订单已支付";
    }
    LocalDateTime now = LocalDateTime.now();
    if (orderDetail.getLockExpire().isBefore(now)) {
        System.err.println(orderDetail.getLockExpire());
        orderDetail.setStatus("订单超时");
        orderDetailMapper.edit(orderDetail);
        orderMapper.timeOut(orderDetail.getOrderId());
        System.err.println("订单已过期: " + id);
        return "订单已过期";
    }


//    new TicketInventoryManager();
//    // 扣减票数
//    boolean success = ticketInventoryManager.deductTickets(orderDetail.getScheduleId(), 1);

    // 更新订单状态
    orderDetail.setStatus("已支付");
    orderDetail.setPayTime(LocalDateTime.now());
    orderDetailMapper.edit(orderDetail);
    orderMapper.commit(orderDetail.getOrderId());
    System.out.println("订单支付成功，班次 " + orderDetail.getScheduleId() + " 剩余票数: " +
            ticketInventoryManager.getRemainingTickets(orderDetail.getScheduleId()));
    return "支付成功";


}

}
